package com.cqc.other.designPattern.strategyPattern.strategy2;

import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileStrategyTest {

    @Test
    public void f1() throws Exception {
        //假设这是上传的文件
        Path dirPath = Paths.get("D:/", "temp", "A", "B", "C");
        if (Files.notExists(dirPath)) {
            //创建多级目录,已经存在再次创建不会报错，也不会再次创建
            dirPath = Files.createDirectories(dirPath);

        }
        File file = dirPath.toFile();
        String fileName = dirPath.getFileName().toString();
        int dotIndex = fileName.lastIndexOf(".");
        String suffix = fileName.substring(dotIndex + 1);

        FileStrategyContext fileStrategyContext = new FileStrategyContext();
        switch (suffix) {
            case "txt":
                fileStrategyContext.setFileStrategy(new TxtFileStrategy());
                break;
            case "csv":
                fileStrategyContext.setFileStrategy(new CsvFileStrategy());
                break;
            case "xls":
                fileStrategyContext.setFileStrategy(new XlsFileStrategy());
                break;
        }
        fileStrategyContext.readFile(file);
    }

    @Test
    public void f2() throws Exception {
        //假设这是上传的文件
        Path dirPath = Paths.get("D:/", "temp");
        Path filePath = dirPath.resolve("a.txt");
        if (Files.notExists(dirPath)) {
            //创建多级目录,已经存在再次创建不会报错，也不会再次创建
            Files.createDirectories(dirPath);
        }
        //a.txt也可能是目录  Files.isRegularFile(filePath)判断path是不是文件，  Files.isDirectory(filePath)判断path是不是目录
        if (Files.exists(filePath)) {
            System.out.println("a3.txt已存在");
        } else {
            Files.createFile(filePath);
        }

        File file = filePath.toFile();


        FileStrategyFactory fileStrategyContext = new FileStrategyFactory();
        //拿到具体的策略
        FileStrategy fileStrategy = fileStrategyContext.getFileStrategy(file);
        fileStrategy.readFile(file);
    }
}
